define(["SzLib", "SzSns", "jquery", "jquery.json"], function(SzLib, SzSns) {

    /**
     * Facebook implementation of SzSns.
     */
    var SzSnsFacebook = function() {
        // Call the parent constructor
        SzSns.call(this);
    };
    // inherit SzSns
    SzSnsFacebook.prototype = new SzSns();
    // correct the constructor pointer because it points to SzSns
    SzSnsFacebook.prototype.constructor = SzSnsFacebook;


    //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
    //-* API Function Overwrites
    //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
    /**
     * 获取玩家信息
     *
     * @see SzSns.prototype.getUserInfo
     */
    SzSnsFacebook.prototype.getUserInfo = function(platformId, callback) {
        return FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                FB.api('/me', {fields: 'id,name,gender,timezone,locale,email,first_name,last_name', access_token:response.authResponse.accessToken}, function(r) {
                    var userInfo = {
                        id: r.id,
                        name: r.name,
                        gender: r.gender,
                        locale: r.location,
                        profile_image_url: 'https://graph.facebook.com/v2.8/' + platformId + '/picture',
                        timezone: r.timezone,
                        email: r.email,
                        first_name: r.first_name,
                        last_name: r.last_name
                    };

                    SZ.APP.callAsFunc("setUserInfo", userInfo);
                    if (typeof callback == 'function') {
                        callback(userInfo);
                    }

                    return userInfo;
                });
            } else {
                FB.login(function() {
                    SZ.SNS.getUserInfo(platformId, callback);
                });
            }
        });
    };

    /**
     * 获取复数玩家信息
     *
     * @see SzSns.prototype.getUserInfos
     */
    SzSnsFacebook.prototype.getUserInfos = function(platformIds, callback) {
        return FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                FB.api('/ids=' + platformIds, {fields: 'id,name', access_token:response.authResponse.accessToken}, function(r) {
                    var userInfos = {};
                    if (typeof r === 'object') {
                        $.each(r, function(platformId, friendInfo) {
                            if (platformId != SZ.PLATFORM_ID) {
                                userInfos[platformId] = {
                                    id: friendInfo.id,
                                    name: friendInfo.name,
                                    profile_image_url: 'https://graph.facebook.com/v2.8/' +  friendInfo.id + '/picture'
                                };
                            }
                        });
                    }
                    SZ.APP.callAsFunc("setUserInfos", userInfos);
                    if (typeof callback == 'function') {
                        callback(userInfos);
                    }

                    return userInfos;
                });
            } else {
                FB.login(function() {
                    SZ.SNS.getUserInfos(platformIds, callback);
                });
            }
        });
    };

    /**
     * 获取好友列表信息
     *
     * @see SzSns.prototype.getFriends
     */
    SzSnsFacebook.prototype.getFriends = function(platformId, callback) {
        return FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                FB.api('/me/friends', {fields: 'id,name', access_token:response.authResponse.accessToken}, function(r) {
                    var userInfos = {};
                    if (typeof r === 'object') {
                        $.each(r.data, function(key, friendInfo) {
                            if (friendInfo.id != SZ.PLATFORM_ID) {
                                userInfos[friendInfo.id] = {
                                    id: friendInfo.id,
                                    name: friendInfo.name,
                                    profile_image_url: 'https://graph.facebook.com/v2.8/' +  friendInfo.id + '/picture'
                                };
                            }
                        });
                    }
                    SZ.APP.callAsFunc("setFriendList", userInfos);
                    if (typeof callback == 'function') {
                        callback(userInfos);
                    }

                    return userInfos;
                });
            } else {
                FB.login(function() {
                    SZ.SNS.getFriends(platformId, callback);
                });
            }
        });
    };

    /**
     * 获取玩家access token的接口
     *
     * @see SzSns.prototype.getAccessToken
     */
    SzSnsFacebook.prototype.getAccessToken = function() {
        return FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                SZ.APP.callAsFunc("setAccessToken", [response.authResponse.accessToken]);
            } else {
                FB.login(function() {
                    SZ.SNS.getAccessToken();
                });
            }
        });
    };

    /**
     * 获取玩家本地化支付，现金单位与汇率的接口
     *
     * @see SzSns.prototype.getCurrency
     */
    SzSnsFacebook.prototype.getCurrency = function(params, callback) {
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                FB.api('/me', {fields: 'currency', access_token:response.authResponse.accessToken}, function(r) {
                    SzLib.log(r);
                    SZ.APP.callAsFunc("setCurrency", r);
                    callback(params, r);
                });
            } else {
                FB.login(function() {
                    SZ.SNS.getCurrency(params, callback);
                });
            }
        });
    };

    /**
     * 服务器生成好feedId和link后，前端调用sendFeed接口，当真正发布feed后，在回调函数中调用as接口，
     * 前端记录已发送feed的类型，并调用后端接口，将feedId传给服务器，服务器更新feedId对应的状态
     *
     * @see SzSns.prototype.sendFeed
     * @param feedId
     * @param feedDefId
     * @param feedInfo
     * @param platformId
     * <pre>
     *    ｛
     *          name:[param, param, ...],
     *          caption:[param, param, ...],
     *          description:[param, param, ...],
     *     ｝
     * </pre>
     */
    SzSnsFacebook.prototype.sendFeed = function(feedId, feedDefId, feedInfo, platformId) {
        var feedUrl = SZ.CANVAS_URL + '/?feedId=' + feedId + '&platformId=' + platformId+ '&act=feed&fb_source=feed';

        // 防止文字超框
        var feedName = SzLib.strReplace(SZ.FEED_JSON[feedDefId].title, feedInfo.name);
        if (feedName.length > 50) {
            feedName = feedName.substring(0, 45) + '...';
        }

        var params = {
            method          : 'feed',
            link            : feedUrl, // feed url
            name            : feedName, // feed name
            caption         : SzLib.strReplace(SZ.FEED_JSON[feedDefId].caption, feedInfo.caption), // feed title
            description     : SzLib.strReplace(SZ.FEED_JSON[feedDefId].description, feedInfo.description), // feed description
            picture         : 'http://' + SZ.IMG_URL + SZ.LANG + '/feed/' + SZ.FEED_JSON[feedDefId].picture // feed picture
        };

        SzLib.log('params:' + JSON.stringify(params));

        $("#gameSwf").addClass("hideSwf");
        $("#gameImage")
            .html('<img src="data:image/jpeg;base64,' + SZ.APP.callAsFunc("getStageImage", []) + '" width="100%">')
            .show();
        FB.ui(params, function(res) {
            $("#gameSwf").removeClass("hideSwf");
            $("#gameImage").html("").hide();
            SZ.APP.callAsFunc("sendFeedCallBack", [res]);
            SzLib.log(res);
        });
    };

    /**
     * 前端调用sendRequest接口，当真正发送request后，在回调函数中调用as接口，
     * 前端记录已发送request的类型和已发送的userId，并调用后端接口，
     * 后端根据userId创建request数据
     *
     * @see SzSns.prototype.sendRequest
     * @param userIds
     * @param requestDefId
     * @param requestInfo
     * <pre>
     *    ｛
     *          title:[param, param, ...],
     *          message:[param, param, ...],
     *     ｝
     * </pre>
     */
    SzSnsFacebook.prototype.sendRequest = function(userIds, requestDefId, requestInfo) {
        // 防止文字超框
        var requestTitle = SzLib.strReplace(SZ.REQUEST_JSON[requestDefId].title, requestInfo.title);
        if (requestTitle.length > 50) {
            requestTitle = requestTitle.substring(0, 45) + '...';
        }

        var params = {
            method          : 'apprequests',
            to              : userIds,
            title           : requestTitle, // request title
            message         : SzLib.strReplace(SZ.REQUEST_JSON[requestDefId].message, requestInfo.message) // request message
        };

        $("#gameSwf").addClass("hideSwf");
        $("#gameImage")
            .html('<img src="data:image/jpeg;base64,' + SZ.APP.callAsFunc("getStageImage", []) + '" width="100%">')
            .show();
        FB.ui(params, function(res) {
            $("#gameSwf").removeClass("hideSwf");
            $("#gameImage").html("").hide();
            SZ.APP.callAsFunc("sendRequestCallBack", [res.request]);
            SzLib.log(res);
        });
    };

    /**
     * 发送sendOpenGraph接口，
     *
     * @see SzSns.prototype.sendOpenGraph
     * @param actionType // e.g: harvest
     * @param objectType // e.g: flower
     * @param graphInfo // json string e.g: [[title,...], [description,...]], 具体需要参考openGraph的文档进行设置，默认为空“[[],[]]”
     */
    SzSnsFacebook.prototype.sendOpenGraph = function(actionType, objectType, graphInfo) {
        var dev = SzLib.getUrlParam('dev');
        var params = {};
        params[objectType] = SzLib.getWindowProtocol() + '//' + SZ.WEB_HOST + '/' + SZ.WWW_RELATIVE_PATH
            + '/index.php?act=graph&source=opengraph_' + actionType + objectType
            + '&user_id=' + SZ.USER_ID
            + '&action=' + actionType
            + '&object=' + objectType
            + '&info=' + graphInfo
            + (dev ? '&dev=' + dev : '');
        FB.api('me/' + SZ.CANVAS_NAME + ':' + actionType, 'post', params, function(res) {
            SzLib.log(res);
        });
    };

    /**
     * @see SzSns.prototype.orderPayment
     */
    SzSnsFacebook.prototype.orderPayment = function(paymentDefId, extra, type) {
        if (typeof(paymentDefId) == "undefined") {
            return;
        }

        var dev = SzLib.getUrlParam('dev');
        var payType;
        if (typeof type != "undefined") {
            payType = type;
        }

        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var addParams = {
                    "token": SZ.TOKEN,
                    "dev": SzLib.getUrlParam('dev')
                };
                SzLib.sendSzReq( // create order data
                    ["payment.create", [SZ.USER_ID, paymentDefId, extra]],
                    function(order) {
                        var serial = new Date().getTime() + '' + (Math.random() * 10000 + '');
                        var params = {};
                        if (payType == "giftcard") {
                            // 礼品卡支付
                            params = {
                                method: 'pay',
                                action: 'redeem',
                                request_id : order.orderId + '_' + serial
                            };
                        } else {
                            // 普通支付
                            var url = SZ.REQUEST_URL + '?token=' + SZ.TOKEN + '&user_id=' + SZ.USER_ID +
                                '&act=product&id=' + paymentDefId + '&serial=' + serial + (dev ? '&dev=' + dev : '');
                            params = {
                                method: 'pay',
                                action: 'purchaseitem',
                                product: url,
                                quantity: 1,
                                request_id : order.orderId + '_' + serial
                            };
                        }

                        if ($("#gameShadow").is(":hidden")) {
                            $("#gameSwf").addClass("hideSwf");
                            $("#gameImage")
                                .html('<img src="data:image/jpeg;base64,' + SZ.APP.callAsFunc("getStageImage", []) + '" width="100%">')
                                .show();
                        }
                        FB.ui(params, function(res) { // request facebook payment dialogue
                            if ($("#gameShadow").is(":hidden")) {
                                $("#gameSwf").removeClass("hideSwf");
                                $("#gameImage").html("").hide();
                            }
                            if (typeof res.error_code == "undefined") {
                                // first pay sign
                                if (extra === 'isFristPay') {
                                    $.extend(addParams, {
                                        "isFirstPay": true
                                    });
                                }

                                SzLib.sendSzReq(
                                    ["page.index", []],
                                    function(r) {
                                        SzLib.log(r);
                                        SZ.APP.paymentSucceed(r);
                                    },
                                    function(r) {
                                        SzLib.log(data);
                                    },
                                    $.extend(addParams, {
                                        "act": "complete",
                                        "res": res,
                                        "signed_request": SZ.PF_TOKEN,
                                        "token": SZ.TOKEN
                                    }),
                                    SZ.IS_COMPRESS
                                );
                            }
                        });
                    },
                    function(data) {
                        SzLib.log(data); // failure
                    },
                    addParams,
                    SZ.IS_COMPRESS
                );
            } else {
                FB.login(function() {
                    SZ.SNS.orderPayment(paymentDefId, extra, type);
                });
            }
        });
    };

    /**
     * 打开邀请好友界面
     *
     * @returns void
     */
    SzSnsFacebook.prototype.inviteBox = function() {
        SzLib.log('facebook invite box');
        SZ.APP.callAsFunc("closeJsPanel", []);
        SZ.APP.callAsFunc("openInviteNeighborsPanel", []);
    };

    return new SzSnsFacebook();

});